<?php

namespace app\admin\controller\store;

use app\admin\model\Admin;
use app\admin\model\AuthDepartment;
use think\Config;
use fast\Random;

use app\admin\model\Department;
use app\common\controller\Backend;
use fast\Tree;
use think\Db;
use Think\Session;
use think\Cache;

/**
 * 仓库管理
 *
 * @icon fa fa-circle-o
 */
class Githouse extends Backend
{

    /**
     * Githouse模型对象
     * @var \app\admin\model\Githouse
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Githouse;
        $this->view->assign("statusList", $this->model->getStatusList());
        $dept = GetBaseInfo('Dept');
        $groupList = collection(AuthDepartment::field('*,parentid as pid')->where('id','in',''.implode(',',$dept).'')->whereOr('parentid','in',''.implode(',',$dept).'')->select())->toArray();

        //print_r($groupdata);die;
        $this->view->assign('groupdata', $groupList);
        $this->view->assign("statusList", $this->model->getStatusList());


    }
    public function init(){

        $info = $this->upload();
        $id  = $_GET['id'];
        if($info['status']==0)$this->error($info['msg']);
        $filePath = ROOT_PATH . DS . 'public' . DS . $info['url'];
        $PHPReader = new \PHPExcel_Reader_Excel2007();
        if (!$PHPReader->canRead($filePath)) {
            $PHPReader = new \PHPExcel_Reader_Excel5();
            if (!$PHPReader->canRead($filePath)) {
                $PHPReader = new \PHPExcel_Reader_CSV();
                if (!$PHPReader->canRead($filePath)) {
                    $this->error(__('Unknown data format'));
                }
            }
        }
        $PHPExcel = $PHPReader->load($filePath); //加载文件
        $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
        $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
        $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
        $maxColumnNumber = \PHPExcel_Cell::columnIndexFromString($allColumn);
        for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
            $val1 = $currentSheet->getCellByColumnAndRow(0, $currentRow)->getValue();
            $val2 = $currentSheet->getCellByColumnAndRow(1, $currentRow)->getValue();
            $val3 = intval($currentSheet->getCellByColumnAndRow(2, $currentRow)->getValue());
            $val4 = intval($currentSheet->getCellByColumnAndRow(3, $currentRow)->getValue());

            if($val3 > 0){
                if (Db::name("stock")->where(array("cid"=>$id,"shopid"=>$val1))->find()){
                    Db::name("stock")->where(array("cid"=>$id,"shopid"=>$val1))->setInc('num',$val3);
                }else{
                    Db::name("stock")->insert(array("cid"=>$id,"shopid"=>$val1,"num"=>$val3,'type'=>$val4));

                }

            }

        }
        $this->success("导入成功");

    }
    protected function upload(){
        Config::set('default_return_type', 'json');
        $file = $this->request->file('file');
        if (empty($file)) {
            $this->error(__('No file upload or server upload limit exceeded'));
        }

        //判断是否已经存在附件
        $sha1 = $file->hash();

        $upload = Config::get('upload');

        preg_match('/(\d+)(\w+)/', $upload['maxsize'], $matches);
        $type = strtolower($matches[2]);
        $typeDict = ['b' => 0, 'k' => 1, 'kb' => 1, 'm' => 2, 'mb' => 2, 'gb' => 3, 'g' => 3];
        $size = (int)$upload['maxsize'] * pow(1024, isset($typeDict[$type]) ? $typeDict[$type] : 0);
        $fileInfo = $file->getInfo();
        $suffix = strtolower(pathinfo($fileInfo['name'], PATHINFO_EXTENSION));
        $suffix = $suffix ? $suffix : 'file';

        $mimetypeArr = explode(',', strtolower($upload['mimetype']));
        $typeArr = explode('/', $fileInfo['type']);

//        //验证文件后缀
//        if ($upload['mimetype'] !== '*' &&
//            (
//                !in_array($suffix, $mimetypeArr)
//                || (stripos($typeArr[0] . '/', $upload['mimetype']) !== false && (!in_array($fileInfo['type'], $mimetypeArr) && !in_array($typeArr[0] . '/*', $mimetypeArr)))
//            )
//        ) {
//            $this->error(__('Uploaded file format is limited'));
//        }
        $replaceArr = [
            '{year}'     => date("Y"),
            '{mon}'      => date("m"),
            '{day}'      => date("d"),
            '{hour}'     => date("H"),
            '{min}'      => date("i"),
            '{sec}'      => date("s"),
            '{random}'   => Random::alnum(16),
            '{random32}' => Random::alnum(32),
            '{filename}' => $suffix ? substr($fileInfo['name'], 0, strripos($fileInfo['name'], '.')) : $fileInfo['name'],
            '{suffix}'   => $suffix,
            '{.suffix}'  => $suffix ? '.' . $suffix : '',
            '{filemd5}'  => md5_file($fileInfo['tmp_name']),
        ];
        $savekey = $upload['savekey'];
        $savekey = str_replace(array_keys($replaceArr), array_values($replaceArr), $savekey);

        $uploadDir = substr($savekey, 0, strripos($savekey, '/') + 1);
        $fileName = substr($savekey, strripos($savekey, '/') + 1);
        //
        $splInfo = $file->validate(['size' => $size])->move(ROOT_PATH . '/public' . $uploadDir, $fileName);
        if ($splInfo) {
            $imagewidth = $imageheight = 0;
            if (in_array($suffix, ['gif', 'jpg', 'jpeg', 'bmp', 'png', 'swf'])) {
                $imgInfo = getimagesize($splInfo->getPathname());
                $imagewidth = isset($imgInfo[0]) ? $imgInfo[0] : $imagewidth;
                $imageheight = isset($imgInfo[1]) ? $imgInfo[1] : $imageheight;
            }
            $params = array(
                'admin_id'    => (int)$this->auth->id,
                'user_id'     => 0,
                'userid'     => $this->auth->userid,
                'username'     => $this->auth->username,
                'filesize'    => $fileInfo['size'],
                'imagewidth'  => $imagewidth,
                'imageheight' => $imageheight,
                'imagetype'   => $suffix,
                'imageframes' => 0,
                'mimetype'    => $fileInfo['type'],
                'url'         => $uploadDir . $splInfo->getSaveName(),
                'uploadtime'  => time(),
                'storage'     => 'local',
                'sha1'        => $sha1,
            );
            $attachment = model("attachment");
            $attachment->data(array_filter($params));
            $attachment->save();
            \think\Hook::listen("upload_after", $attachment);
            return array(
                'status'=>1,
                'url' => $uploadDir . $splInfo->getSaveName()
            );
        } else {
            // 上传失败获取错误信息
            return array("status"=>0,"msg"=>$file->getError());
        }
    }
        public function index()
        {
            //设置过滤方法
            $this->request->filter(['strip_tags']);
            if ($this->request->isAjax()) {
                //如果发送的来源是Selectpage，则转发到Selectpage
                if ($this->request->request('keyField')) {

                    return $this->selectpage();
                }
                list($where, $sort, $order, $offset, $limit) = $this->buildparams();
                $fiter =$this->request->request('filter');
                $gname = json_decode($fiter,1);
                $search =$this->request->request('search');
                if ($gname)   {
                    $title=$gname['gname'];
                } else{
                    if ($search!=''){
                        $title=$search;
                    }else{
                        $title='';
                    }
                }
                if ($title!=''){
                    $where=[];

                    $where['gname']=array('like',"%{$title}%");

                }
               // var_dump($where);
                $total = $this->model
                    ->where($where)
                    ->order($sort, $order)
                    ->count();

                $list = $this->model
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

                $list = collection($list)->toArray();
                foreach ($list as $k=>$v){
                    $list[$k]['lxr']=$this->getPublisher($v['manger']);
                }
                $result = array("total" => $total, "rows" => $list);

                return json($result);
            }
            return $this->view->fetch();
        }
    protected function getPublisher($id){
        $db = new Admin();
        $info = $db->where(array("userid"=>$id))->field('username')->find();
        if (!$info)return '';
        return $info['username'];
    }
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : true) : $this->modelValidate;
                        $this->model->validate($validate);
                    }
                    $post = $this->request->post();
                    $admin = Session::get('admin');
                    $userid = $admin['userid'];
                    if ( $this->model->where(array('manger'=>$post['row']['manger']))->find()){
                        $this->error("此用户已是其他仓库管理员");
                    }
                    $result = $this->model->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($this->model->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $depdb = new AuthDepartment();
        $dep = collection($depdb->where("id=1 or parentid=2")->order('id asc')->select()->toArray());

        $this->assign("dep",$dep);
        return $this->view->fetch();
    }

    public function edit($ids = NULL)
    {
        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = basename(str_replace('\\', '/', get_class($this->model)));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : true) : $this->modelValidate;
                        $row->validate($validate);
                    }
                    $post = $this->request->post();
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $depdb = new AuthDepartment();
        $dep = collection($depdb->where("id=1 or parentid=2")->order('id asc')->select()->toArray());

        $this->assign("dep",$dep);

        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

}